import com.sun.tools.javac.Main;
import utils.DBUtil;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo01_DriverManager {
    public static void main(String[] args) {
        //通过驱动管理类 DriverManager 的静态⽅法获取数据库连接对象
        Connection connection = null;
        //用来执行sql，并接受返回对象
        Statement statement = null;
        //用来接收结果集
        ResultSet resultSet = null;
        try {
            //加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");

            //创建Statement对象，
            statement = connection.createStatement();

            //定义并执行SQL
            //1)定义SQL
            System.out.println("请输入学生姓名：");
            Scanner scanner = new Scanner(System.in);
            // 接收用户的输入
            String name = scanner.next();
            String sql = "select student_id, sn, name, mail, class_id from student where name = '" + name + "'";
            //2)执行SQL，接收结果集
            resultSet = statement.executeQuery(sql);

            //对结果集进行遍历，获取数据
            // resultSet.next()如果一下条有记录，返回true,没有则返回false
            while (resultSet.next()) {
                // 获取学生Id
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}, 学号={1}, 学生姓名={2}, 邮箱={3}, 班级编号={4}", stuId, stuSn,
                        stuName, stuMail, classId));
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 不管是否出现异常都要释放资源，所以在finally里面释放资源。
            // 依次释放资源，关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}
